import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sweet_lib/main.dart';
import 'package:flutter_sweet_lib/project_demo_page/youpin_pages/cart_page.dart';
import 'package:flutter_sweet_lib/project_demo_page/youpin_pages/details.dart';
import 'package:flutter_sweet_lib/project_demo_page/youpin_pages/goods_details_page.dart';
import 'package:flutter_sweet_lib/project_demo_page/youpin_pages/page_0.dart';
import 'package:flutter_sweet_lib/project_demo_page/youpin_pages/page_1.dart';
import 'package:flutter_sweet_lib/project_demo_page/youpin_pages/pinwei_page.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class YouPinAllPage extends StatefulWidget {
  @override
  _YouPinAllPageState createState() => _YouPinAllPageState();
}

class _YouPinAllPageState extends State<YouPinAllPage> {
  int _currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    Widget widget =
        const Center(child: Text("开发中...", style: TextStyle(fontSize: 38.0)));
    switch (_currentIndex) {
      case 0:
        widget = YouPinFirstPage();
        break;

      case 1:
        widget = ClassifyPage();
        break;

      case 2:
        widget = PinWeiPage();
        break;

      case 3:
        widget = YouPinCartPage();
        break;

      case 4:
        widget = DetailsPage();
    }
    return Scaffold(
      body: widget,
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home), title: Text("首页")),
          BottomNavigationBarItem(
              icon: Icon(Icons.calendar_view_day), title: Text("分类")),
          BottomNavigationBarItem(icon: Icon(Icons.apps), title: Text("品味")),
          BottomNavigationBarItem(
              icon: Icon(Icons.shopping_cart), title: Text("购物车")),
          BottomNavigationBarItem(icon: Icon(Icons.person), title: Text("我的")),
        ],
        type: BottomNavigationBarType.fixed,
        currentIndex: _currentIndex,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
      ),
    );
  }
}



class ClassifyModel {
  final String title;
  final String subTitle;
  final bool topFlag;
  final List<String> list;

  const ClassifyModel(
      {this.title, this.subTitle, this.topFlag = false, this.list});
}

///
/// 分类页面
class ClassifyPage extends StatefulWidget {
  @override
  _ClassifyPageState createState() => _ClassifyPageState();
}

class _ClassifyPageState extends State<ClassifyPage> {
  List<ClassifyModel> _classifyList = [
    ClassifyModel(
        title: "有品推荐",
        subTitle: "有品生活哲学",
        topFlag: true,
        list: ["运动健身", "逍遥四方", "科技达人", "销量榜单", "男士精选", "品质生活"]),
    ClassifyModel(title: "家居家纺", subTitle: "悦享品质格调", list: [
      "居家热卖",
      "新品推荐",
      "床垫",
      "秋冬专区",
      "灯具",
      "家具",
      "被子",
      "枕头",
      "床品件套",
      "家居收纳",
      "厨房卫浴",
      "家饰花卉",
      "布艺软装",
      "毛巾浴巾"
    ]),
    ClassifyModel(title: "家用电器", subTitle: "乐享生活便捷", list: [
      "新品推荐",
      "春季换新",
      "清洁电器",
      "生活电器",
      "洗衣机",
      "冰箱",
      "净水器",
      "空气净化器",
      "新风系统",
      "空调/风扇",
      "厨房家电",
      "配件耗材"
    ]),
    ClassifyModel(title: "智能家庭", subTitle: "理想生活仪式感", list: [
      "智能家庭套装",
      "安防",
      "网关/传感器",
      "路由器",
      "开关插座",
      "酷玩",
      "相机",
      "穿戴",
      "健康"
    ]),
    ClassifyModel(title: "餐具厨房", subTitle: "享受下厨房的乐趣", list: [
      "热卖爆品",
      "新品上线",
      "厨房电器",
      "锅具",
      "杯壶",
      "刀剪砧板",
      "厨房净水",
      "茶咖酒具"
          "功能厨具",
      "餐具",
      "厨房清洁",
      "保险收纳"
    ]),
    ClassifyModel(title: "服装配饰", subTitle: "享受下厨房的乐趣", list: [
      "热卖爆品",
      "新品上线",
      "厨房电器",
      "锅具",
      "杯壶",
      "刀剪砧板",
      "厨房净水",
      "茶咖酒具"
          "功能厨具",
      "餐具",
      "厨房清洁",
      "保险收纳"
    ]),
    ClassifyModel(title: "鞋靴箱包", subTitle: "享受下厨房的乐趣", list: [
      "热卖爆品",
      "新品上线",
      "厨房电器",
      "锅具",
      "杯壶",
      "刀剪砧板",
      "厨房净水",
      "茶咖酒具"
          "功能厨具",
      "餐具",
      "厨房清洁",
      "保险收纳"
    ]),
    ClassifyModel(title: "手机电脑", subTitle: "享受下厨房的乐趣", list: [
      "热卖爆品",
      "新品上线",
      "厨房电器",
      "锅具",
      "杯壶",
      "刀剪砧板",
      "厨房净水",
      "茶咖酒具"
          "功能厨具",
      "餐具",
      "厨房清洁",
      "保险收纳"
    ]),
    ClassifyModel(title: "电视影音", subTitle: "享受下厨房的乐趣", list: [
      "热卖爆品",
      "新品上线",
      "厨房电器",
      "锅具",
      "杯壶",
      "刀剪砧板",
      "厨房净水",
      "茶咖酒具"
          "功能厨具",
      "餐具",
      "厨房清洁",
      "保险收纳"
    ]),
    ClassifyModel(title: "运动健康", subTitle: "享受下厨房的乐趣", list: [
      "热卖爆品",
      "新品上线",
      "厨房电器",
      "锅具",
      "杯壶",
      "刀剪砧板",
      "厨房净水",
      "茶咖酒具"
          "功能厨具",
      "餐具",
      "厨房清洁",
      "保险收纳"
    ]),
    ClassifyModel(title: "出门户外", subTitle: "享受下厨房的乐趣", list: [
      "热卖爆品",
      "新品上线",
      "厨房电器",
      "锅具",
      "杯壶",
      "刀剪砧板",
      "厨房净水",
      "茶咖酒具"
          "功能厨具",
      "餐具",
      "厨房清洁",
      "保险收纳"
    ]),
    ClassifyModel(title: "洗护美妆", subTitle: "享受下厨房的乐趣", list: [
      "热卖爆品",
      "新品上线",
      "厨房电器",
      "锅具",
      "杯壶",
      "刀剪砧板",
      "厨房净水",
      "茶咖酒具"
          "功能厨具",
      "餐具",
      "厨房清洁",
      "保险收纳"
    ]),
    ClassifyModel(title: "日杂文创", subTitle: "享受下厨房的乐趣", list: [
      "热卖爆品",
      "新品上线",
      "厨房电器",
      "锅具",
      "杯壶",
      "刀剪砧板",
      "厨房净水",
      "茶咖酒具"
          "功能厨具",
      "餐具",
      "厨房清洁",
      "保险收纳"
    ]),
    ClassifyModel(title: "母婴亲子", subTitle: "享受下厨房的乐趣", list: [
      "热卖爆品",
      "新品上线",
      "厨房电器",
      "锅具",
      "杯壶",
      "刀剪砧板",
      "厨房净水",
      "茶咖酒具"
          "功能厨具",
      "餐具",
      "厨房清洁",
      "保险收纳"
    ]),
  ];

  ScrollController _scrollController = ScrollController(initialScrollOffset: 0);

  PageController _pageController =
      PageController(initialPage: 0, keepPage: true);

  @override
  void initState() {
    super.initState();
  }

  final height = 45.0;

  int _currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          elevation: 0.0,
          title: SearchInputWidget(showText: "搜一搜"),
          leading: YPLoginWidget(),
          backgroundColor: Colors.white),
      body: Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: ListView(
              key: PageStorageKey("type"),
              controller: _scrollController,
              children: _classifyList.map((cName) {
                return InkWell(
                  child: Container(
                    height: height,
                    color: cName.topFlag ? Colors.white : Colors.grey[200],
                    child: Row(
                      children: <Widget>[
                        Offstage(
                            offstage: !cName.topFlag,
                            child: Container(
                                color: bodyColor,
                                width: 3.0,
                                height: 25.0)),
                        const SizedBox(width: 8.0),
                        Container(
                            child: Text(cName.title,
                                style: TextStyle(
                                    color: cName.topFlag
                                        ? bodyColor
                                        : null,
                                    fontSize: cName.topFlag
                                        ? 15.0
                                        : Theme.of(context)
                                            .textTheme
                                            .body2
                                            .fontSize)),
                            alignment: Alignment.center,
                            padding: EdgeInsets.symmetric(horizontal: 5.0)),
                      ],
                    ),
                  ),
                  onTap: () => _classifyItemOnTap(cName),
                );
              }).toList(),
            ),
          ),
          Expanded(
              flex: 3,
              child: PageView(
                onPageChanged: _pageChanged,
                scrollDirection: Axis.vertical,
                controller: _pageController,
                children: _classifyList.map((cName) {
                  return Padding(
                    padding: EdgeInsets.all(10.0),
                    child: RecommendClassifyPage(
                      title: cName.subTitle,
                      list: cName.list,
                      topCallBack: () {
                        print("top call back");
                        if (_currentIndex == 0) {
                          return;
                        }
                        int index = _currentIndex - 1;
                        _pageChanged(index);
                        _pageController.animateToPage(index,
                            duration: Duration(milliseconds: 500),
                            curve: Curves.easeInOut);
                      },
                      bottomCallBack: () {
                        print("bottom call back");
                        if ((_currentIndex + 1) == _classifyList.length) {
                          return;
                        }
                        int index = _currentIndex + 1;
                        _pageChanged(index);
                        _pageController.animateToPage(index,
                            duration: Duration(milliseconds: 500),
                            curve: Curves.easeInOut);
                      },
                    ),
                  );
                }).toList(),
              ))
        ],
      ),
    );
  }

  _classifyItemOnTap(ClassifyModel cName) {
    final _newList = <ClassifyModel>[];
    int index = 0;
    for (int i = 0; i < _classifyList.length; i++) {
      final model = _classifyList[i];
      if (model.title == cName.title) {
        index = i;
        _newList.add(ClassifyModel(
            title: model.title,
            subTitle: model.subTitle,
            topFlag: true,
            list: model.list));
        _pageController.animateToPage(i,
            duration: Duration(milliseconds: 1), curve: Curves.easeInOut);
      } else {
        _newList.add(ClassifyModel(
            title: model.title,
            subTitle: model.subTitle,
            topFlag: false,
            list: model.list));
      }
    }
    setState(() {
      _classifyList = _newList;
      _currentIndex = index;
    });
  }

  void _pageChanged(int index) {
    _scrollController.animateTo((height * index),
        duration: Duration(milliseconds: 500), curve: Curves.easeInOut);
    final model = _classifyList[index];
    final _newList = _classifyList.map((m) {
      if (m.title == model.title) {
        return ClassifyModel(
            title: model.title,
            subTitle: model.subTitle,
            topFlag: true,
            list: model.list);
      } else {
        return ClassifyModel(
            title: m.title, subTitle: m.subTitle, topFlag: false, list: m.list);
      }
    }).toList();
    setState(() {
      _classifyList = _newList;
      _currentIndex = index;
    });
  }
}

class RecommendClassifyPage extends StatefulWidget {
  final List<String> list;
  final String title;
  final VoidCallback topCallBack;
  final VoidCallback bottomCallBack;

  const RecommendClassifyPage(
      {this.list, this.title, this.topCallBack, this.bottomCallBack});

  @override
  _RecommendClassifyPageState createState() => _RecommendClassifyPageState();
}

class _RecommendClassifyPageState extends State<RecommendClassifyPage> {
  final ScrollController _controller =
      ScrollController(keepScrollOffset: true, initialScrollOffset: 1);


  @override
  void initState() {
    super.initState();
    _controller.addListener(() {
      if (_controller.position.atEdge) {
        print("${_controller.position.pixels}");
      }

      if (_controller.position.maxScrollExtent == _controller.position.pixels) {
        print("bottom, ${_controller.position.pixels}");
        widget.bottomCallBack();
      }

      if (_controller.position.minScrollExtent == _controller.position.pixels) {
        print("top, ${_controller.position.pixels}");
        widget.topCallBack();
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Widget child = Column(
      children: <Widget>[
        Container(height: 100.0, color: Colors.grey[200]),
        const SizedBox(height: 10.0),
        Container(
            alignment: Alignment.center,
            child: Text("—  ${widget.title}  —",
                style: TextStyle(color: Colors.grey, fontSize: 13.0))),
        const SizedBox(height: 20.0),
        Wrap(
          spacing: 12.0,
          runSpacing: 12.0,
          children: widget.list.map((s) {
            return InkWell(
              child: Column(children: [
                Container(width: 70.0, height: 70.0, color: Colors.grey[200]),
                Text("${s}", style: TextStyle(fontSize: 9.0)),
              ]),
              onTap: () {
                Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                  return Recommend2Page(model: ClassifyModel(title: widget.title, list: widget.list));
                }));
              },
            );
            // Recommend2Page
          }).toList(),
        ),
      ],
    );
    return SingleChildScrollView(
      controller: _controller,
      child: child,
    );
  }
}

class YouPinFirstPage extends StatefulWidget {
  @override
  _YouPinFirstPageState createState() => _YouPinFirstPageState();
}

class _YouPinFirstPageState extends State<YouPinFirstPage> {
  List<TypeModel> _typeList = [
    TypeModel(no: 0, typeName: '推荐'),
    TypeModel(no: 1, typeName: '手机'),
    TypeModel(no: 2, typeName: '家电'),
    TypeModel(no: 3, typeName: '居家'),
    TypeModel(no: 4, typeName: '智能'),
    TypeModel(no: 5, typeName: '饮食'),
    TypeModel(no: 6, typeName: '餐厨'),
    TypeModel(no: 7, typeName: '服饰'),
    TypeModel(no: 8, typeName: '鞋包'),
    TypeModel(no: 9, typeName: '笔记本'),
    TypeModel(no: 10, typeName: '影音'),
    TypeModel(no: 11, typeName: '健康'),
    TypeModel(no: 12, typeName: '出行'),
    TypeModel(no: 13, typeName: '洗护'),
    TypeModel(no: 14, typeName: '日杂'),
    TypeModel(no: 15, typeName: '母婴'),
    TypeModel(no: 16, typeName: '配件'),
    TypeModel(no: 17, typeName: '品牌'),
  ];

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
        length: _typeList.length,
        child: Scaffold(
          appBar: AppBar(
            elevation: 0.0,
            backgroundColor: Colors.white,
            leading: YPLoginWidget(),
            title: SearchInputWidget(onTap: () {}, showText: "搜一搜"),
            actions: <Widget>[
              IconButton(
                icon: Icon(Icons.notifications_none, color: Colors.grey[500]),
                onPressed: () {},
              )
            ],
            bottom: TabBar(
                isScrollable: true,
                tabs: _typeList.map((model) {
                  return Tab(
                    child: Text(
                      model.typeName,
                      style: TextStyle(
                          color: Theme.of(context).textTheme.title.color),
                    ),
                  );
                }).toList()),
          ),
          body: TabBarView(
              children: _typeList.map((model) {
            Widget widget = const Center(
                child: Text("开发中...", style: TextStyle(fontSize: 38.0)));
            switch (model.no) {
              case 0:
                widget = RecommendPage();
                break;
            }
            return RefreshIndicator(
                child: widget,
                onRefresh: () async {
                  await Future.delayed(const Duration(seconds: 2), () {});
                });
          }).toList()),
        ));
  }
}

///
///  Theme(
//              data: Theme.of(context).copyWith(
//                  canvasColor: Colors.green,
//                  textTheme: Theme
//                      .of(context)
//                      .textTheme
//                      .copyWith(caption: TextStyle(color: Colors.red))),
//              child:

class TypeListWidgetByWrap extends StatelessWidget {
  final List<TypeModel> typeList;
  final ValueChanged<TypeModel> onTap;
  final VoidCallback showAllTypeFun;

  const TypeListWidgetByWrap({this.typeList, this.onTap, this.showAllTypeFun});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Padding(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text("全部分类"),
                InkWell(
                    child:
                        Icon(Icons.keyboard_arrow_up, color: Colors.grey[500]),
                    onTap: showAllTypeFun)
              ],
            ),
            padding: EdgeInsets.symmetric(horizontal: 10.0)),
        Wrap(
          children: typeList.map((type) {
            return Padding(
              padding: EdgeInsets.symmetric(horizontal: 8.0),
              child: OutlineButton(
                  onPressed: () => onTap(type), child: Text(type.typeName)),
            );
          }).toList(),
        )
      ],
    );
  }
}

class TypeModel {
  final int no;
  final String typeName;
  final bool selected;

  const TypeModel({this.no, this.typeName, this.selected = false});
}

class TypeItemWidget extends StatelessWidget {
  final TypeModel typeModel;

  const TypeItemWidget({this.typeModel});

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Container(
            height: 15.0,
            width: 50.0,
            alignment: Alignment.center,
            padding: EdgeInsets.only(left: 10.0, right: 10.0, bottom: 3.0),
            child: Text(typeModel.typeName,
                style: TextStyle(
                    color: typeModel.selected
                        ? Theme.of(context).primaryColor
                        : null))),
        Offstage(
            offstage: !typeModel.selected,
            child: Container(
                height: 3.0,
                width: 25.0,
                color: typeModel.selected
                    ? Theme.of(context).primaryColor
                    : null)),
      ],
    );
  }
}

class YPLoginWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
        alignment: Alignment.center,
        padding: EdgeInsets.only(left: 10.0),
        child: Text(
          "有品",
          style: TextStyle(
              color: Colors.grey, fontSize: 22.0, fontWeight: FontWeight.bold),
        ));
  }
}

class SearchInputWidget extends StatelessWidget {
  final VoidCallback onTap;
  final String showText;

  SearchInputWidget({this.onTap, this.showText});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.all(5.0),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(3.0), color: Colors.grey[200]),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Icon(
              Icons.search,
              size: 18.0,
              color: Colors.grey,
            ),
            const SizedBox(width: 5.0),
            Text(showText, style: TextStyle(fontSize: 15.0, color: Colors.grey))
          ],
        ),
      ),
    );
  }
}
